package engine.motionDetection;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.media.Player;
import javax.media.control.FrameGrabbingControl;

import engine.events.HINBEventListener;
import engine.events.NewCoordEvent;
import engine.videoCapture.GrabFrame;

/**
 * EngineMotionDetectionInterface is a thread that offers handles for 
 * the motion detection
 * @author Manu
 *
 */
public class EngineMotionDetectionInterface extends Thread{
	/* *********************************************************
	 * Attributes
	 * ********************************************************* */
	private List<HINBEventListener> _listeners;
	private boolean _running;
	private FrameGrabbingControl _frameGrabbingControl;
	private BufferedImage _background;
	private BufferedImage _foreground;
	
	
	/* *********************************************************
	 * Constructor(s)
	 * ********************************************************* */
	public EngineMotionDetectionInterface(Player ply){
		super();
		System.out.println("engine.motionDetection : EngineMotionDetectionInterface");
		_listeners = new ArrayList<HINBEventListener>();
		_running = false;
		_frameGrabbingControl = (FrameGrabbingControl)ply.getControl("" +
				"javax.media.control.FrameGrabbingControl");
	}
	
	public synchronized void addEventListener(HINBEventListener newListener){
		System.out.println("engine.motionDetection : addEventListener");
		_listeners.add(newListener);
	}
	public synchronized void removeEventListener(HINBEventListener existingListener){
		System.out.println("engine.motionDetection : removeEventListener");
		_listeners.remove(existingListener);
	}
	
	public void startMotionDetection(){
		System.out.println("engine.motionDetection : startMotionDetection");
		_running = true;
		this.start();
	}
	
	/**
	 * run runs the motion detection
	 */
	@Override
	public void run() {
				
		super.run();
		System.out.println("engine.motionDetection : run");
		//Get first background image
		_background = GrabFrame.doGrabFrame(_frameGrabbingControl);
		while(_running){
			//one motiondetection's step
			//get foreground
			_foreground = GrabFrame.doGrabFrame(_frameGrabbingControl);
			
			int pos[] = ObjectTracking.track(_background,_foreground);
			int x = pos[0];
			int y = pos[1];
			if((x!=-1)&&(y!=-1)){
				this.fireEvent(new NewCoordEvent(this, x, y));
			}
			_background=_foreground;
		}
	}
	
/**
 * fireEvent send an event
 * @param evt
 */
	private synchronized void fireEvent(NewCoordEvent evt){
		System.out.println("engine.motionDetection : fireEvent");
		Iterator<HINBEventListener> ite = _listeners.iterator();
		while(ite.hasNext()){
			ite.next().handleNewEvent(evt);
		}
	}
}
